/**
 * Created by gongxun on 17/6/8.
 */

//搜寻结构
var KwxBranchArray = function(){
    var that = {};

    that.cardsLeft = [];

    that.laiziCount = 0;

    that.mKwxCardGroup = new KwxCardGroup();

    return that;
};

//一次结构
var KwxCardGroup = function(){
    var that = {};

    //-1:emptr  0:chi  1:triple  2:pair
    that.type = -1;

    that.cards = [];

    return that;
};

var KwxWinGroup = function(){
    var that = {};

    that.mKwxCardGroups = [];

    return that;
};

var KwxAutoRobot = function(){
    var that = {};

    that.tableStatus = null;

    that.mySeatUser = null;

    //吃
    that.grouptype_eat = 0;
    //碰
    that.grouptype_triple = 1;
    //将
    that.grouptype_pair = 2;

    that.onCheckAutoPlayCard = function(tableStatus){

        return;
        //过滤一遍
        if (mo.gameUserInfo.uid != "900" && mo.gameUserInfo.uid != "901" && mo.gameUserInfo.uid != "90048"){
            if (mo.gameHelper.testVersion != 1){
                return;
            }
        }

        that.tableStatus = tableStatus;
        that.mySeatUser = that.tableStatus["SeatUser" + that.tableStatus.MySeat];

        var isMyControl = that.checkMyControl();

        //自己出牌
        if (isMyControl){
            //听牌了就不管了
            if (that.mySeatUser.OpenTing){

            }else{
                //推荐出牌
                mo.kwxTable.mTestLayer.stopAllActions();
                mo.kwxTable.mTestLayer.runAction(
                    cc.sequence(
                        cc.delayTime(0.5),
                        cc.callFunc(function() {
                            that.autoPlay()
                        })
                    )
                );
            }
        }else {
            //别人出牌 不管了
        }
    };

    that.checkMyControl = function(){
        if (that.tableStatus == null){
            return false;
        }

        var NowSeat = that.tableStatus.NowSeat;
        if (NowSeat.length == 0){
            return false;
        }else if (NowSeat.length == 1){
            return NowSeat[0] == that.tableStatus.MySeat;
        }else{
            return false;
        }
    };

    that.autoPlay = function(){
        //可以做的操作
        var control = {};

        var mySeatUser = that.mySeatUser;
        for (var i = 0; i < mySeatUser.NewActionList.length; i++){
            var actionRequestkwx = mySeatUser.NewActionList[i];
            var code = actionRequestkwx.code;
            if (control[code.toString()] == undefined){
                control[code.toString()] = [];
            }
            control[code.toString()].push(actionRequestkwx);
            // if (code == 0){
            //     control[code.toString()] = 1;
            // }else if (code == 2){
            //     control[code.toString()] = 1;
            // }else if (code == 3){
            //
            // }else if (code == 4 || code == 5 || code == 6){
            //
            // }
        }

        var controlFuncs = [
            that.playHu,
            that.playLiang,
            that.playGang,
            that.playGang,
            that.playGang,
            that.playPeng,
            that.playGuo,
            that.playCard
        ];

        var controlActions = [
            control["3"],
            control["0"],
            control["4"],
            control["5"],
            control["6"],
            control["2"],
            control["8"],
            control["7"]
        ];

        for (var i = 0; i < controlFuncs.length; i++){
            var isSend = controlFuncs[i](controlActions[i]);
            if (isSend){
                break;
            }
        }
    };

    that.playHu = function(actions){
        if (that.checkPlayActions(actions)){

            mo.kwxTableStatus.sendOpenCard(actions[0]);
            return true;
        }else{
            return false;
        }
    };

    that.playLiang = function(actions){
        if (that.checkPlayActions(actions)){

            var tingNums = [];
            var tingNumLefts = [];

            var openTingWGS = actions[0].Cg;
            for (var i = 0; i < openTingWGS.Cs.length; i++) {
                tingNums.push(openTingWGS.Cs[i]);
            }
            tingNums = mo.gameHelper.getUniqueArray(tingNums);

            for (var i = 0; i < tingNums.length; i++){
                var left = 0;

                var feipai = tingNums[i];
                var huNums = mo.kwxTableStatus.getMyHuNums(feipai);
                for (var j = 0; j < huNums.length; j++){
                    left += mo.kwxTableStatus.getLeftCardCount(huNums[j]);
                }

                tingNumLefts.push(left);
            }

            var sendCard = tingNums[0];
            var maxLefts = tingNumLefts[0];
            for (var i = 0; i < tingNumLefts.length; i++){
                if (tingNumLefts[i] > maxLefts){
                    sendCard = tingNums[i];
                    maxLefts = tingNumLefts[i];
                }
            }

            mo.kwxTableStatus.sendLiangTingCard([sendCard], []);

            return true;
        }else{
            return false;
        }
    };

    that.playGang = function(actions){
        if (that.checkPlayActions(actions)){

            mo.kwxTableStatus.sendOpenCard(actions[0]);
            return true;
        }else{
            return false;
        }
    };

    that.playPeng = function(actions){
        if (that.checkPlayActions(actions)){

            mo.kwxTableStatus.sendOpenCard(actions[0]);
            return true;
        }else{
            return false;
        }
    };

    that.playGuo = function(actions){
        if (that.checkPlayActions(actions)){

            mo.kwxTableStatus.sendOpenCard(actions[0]);
            return true;
        }else{
            return false;
        }
    };

    that.playCard = function(actions){
        if (that.checkPlayActions(actions)){
            //手牌
            var inhandCards = that.mySeatUser.HandCards;
            inhandCards = inhandCards.sort(function(a, b){
                return a - b;
            });

            //危险牌
            var dangerCards = [];
            for (var i = 1; i <= 3; i++){
                var seatUser = that.tableStatus["SeatUser" + i];
                if (seatUser == null){
                    continue;
                }
                if (i == that.tableStatus.MySeat){
                    continue;
                }

                if (seatUser.OpenTing){
                    dangerCards = dangerCards.concat(seatUser.TingCards);
                }
            }

            //去掉重复
            dangerCards = mo.gameHelper.getUniqueArray(dangerCards);

            //去掉危险牌的手牌
            var safeCards = mo.gameHelper.getFilterArrayForArray(inhandCards, dangerCards);

            //随机出牌
            // var playCard = safeCards[parseInt(Math.random() * safeCards.length)];

            //打乱最少的牌
            var playCard = that.getBestCard(inhandCards, dangerCards);

            cc.log("应该打出的手牌是" + playCard);

            mo.kwxTableStatus.sendPlayCard(playCard);
            return true;
        }else{
            return false;
        }
    };

    that.checkPlayActions = function(actions){
        if (actions != undefined && actions.length != 0){
            return true;
        }

        return false;
    };

    that.getBestCard = function(inhandCards, dangerCards){
        var safeCards = mo.gameHelper.getFilterArrayForArray(inhandCards, dangerCards);
        safeCards = safeCards.sort(function(a, b){
            return a - b;
        });
        safeCards = mo.gameHelper.getUniqueArray(safeCards);

        var lackCard = that.findLackCard(inhandCards, safeCards);
        if (lackCard != -1){
            return lackCard;
        }

        var minIndex = 0;
        var minIndexNum = 14;
        for (var i = 0; i < safeCards.length; i++){
            var lessCount = that.findLessCount(safeCards[i], inhandCards, dangerCards);

            if (lessCount < minIndexNum){
                minIndexNum = lessCount;
                minIndex = i;
            }
        }

        return safeCards[minIndex];
    };

    that.findLessCount = function(playCard, inhandCards, dangerCards){
        //尽可能多的找可以凑成3张 2张 3顺的牌
        //返回剩下最少的牌
        var findCards = mo.gameHelper.getFilterArrayForArray(inhandCards, [playCard]);

        var winGroups = that.branch(findCards.slice(0), false, 1, []);

        var showMsgStrs = ["吃", "碰", "将"];

        var minLessCount = 14;

        cc.log("计算打出牌是" + playCard + "的情况");
        for (var i = 0; i < winGroups.length; i++){
            var winGroup = winGroups[i];
            var cardGroups = winGroup.mKwxCardGroups;
            var lessCount = 14;

            cc.log("第" + i + "种情况");
            for (var j = 0; j < cardGroups.length; j++){
                var groupType = cardGroups[j].type;
                var cardNums = cardGroups[j].cards;
                var msg = showMsgStrs[groupType] + "," + cardNums.join();
                cc.log(msg);

                if (groupType == that.grouptype_eat || groupType == that.grouptype_triple){
                    lessCount -= 3;
                }else if (groupType == that.grouptype_pair){
                    lessCount -= 2;
                }
            }
            cc.log("少" + lessCount + "张牌");

            if (lessCount < minLessCount){
                minLessCount = lessCount;
            }
        }
        cc.log("---------------------------------------");

        return minLessCount;
    };

    that.branch = function(cards, isCanPair, laizi, branchArrays){
        // cc.log("剩余手牌:" + cards.length);

        var result = [];

        var types = [that.grouptype_eat, that.grouptype_triple, that.grouptype_pair];
        var isFind = false;
        for (var index = 0; index < types.length; index++) {
            var type = types[index];
            if (type == that.grouptype_pair && isCanPair){
                //已经找到了将 返回
                continue;
            }

            var branchArray = new KwxBranchArray();

            switch (type){
                case that.grouptype_eat:
                    that.matchEat(cards.slice(0), laizi, branchArray);
                    break;
                case that.grouptype_triple:
                    that.matchTriple(cards.slice(0), laizi, branchArray);
                    break;
                case that.grouptype_pair:
                    that.matchAnyPair(cards.slice(0), laizi, branchArray);
                    break;
            }

            if (branchArray.mKwxCardGroup.type == -1){
                //未找到
                continue;
            }

            isFind = true;
            var newBranchArrays = branchArrays.slice(0);
            newBranchArrays.push(branchArray);
            var winGroups = that.branch(branchArray.cardsLeft.slice(0), type == that.grouptype_pair || isCanPair, branchArray.laiziCount, newBranchArrays.slice(0));
            result = result.concat(winGroups);
        }

        //一直找到不能再找为止
        if (!isFind){
            var winGroup = new KwxWinGroup();
            for (var i = 0; i < branchArrays.length; i++){
                var branchArray = branchArrays[i];
                winGroup.mKwxCardGroups.push(branchArray.mKwxCardGroup);
            }

            result.push(winGroup);
        }

        return result;
    };

    that.matchEat = function(cards, laizi, branchArray){
        if (cards.length < 3){
            return;
        }

        for (var i = 0; i < cards.length; i++){
            var card = cards[i];
            if (card > 80){
                //去掉风
                continue;
            }

            for (var j = 0; j < 3; j++){
                var num1 = card - 2 + j;
                var num2 = num1 + 1;
                var num3 = num1 + 2;

                if (num1 % 10 == 0 || num2 % 10 == 0 || num3 % 10 == 0){
                    continue;
                }else{
                    var eatArrays = [num1, num2, num3];

                    var findCard = that.findCardUseLaizi(cards, laizi, eatArrays);
                    if (findCard[0] == 1){
                        branchArray.cardsLeft = findCard[2];
                        branchArray.laiziCount = laizi - findCard[1];
                        branchArray.mKwxCardGroup.type = that.grouptype_eat;
                        branchArray.mKwxCardGroup.cards = eatArrays;
                        return;
                    }
                }
            }
        }
    };

    that.matchTriple = function(cards, laizi, branchArray){
        for (var i = 0; i < cards.length; i++){
            var card = cards[i];
            var arrays = [card, card, card];

            var findCard = that.findCardUseLaizi(cards, laizi, arrays);
            if (findCard[0] == 1){
                branchArray.cardsLeft = findCard[2];
                branchArray.laiziCount = laizi - findCard[1];
                branchArray.mKwxCardGroup.type = that.grouptype_triple;
                branchArray.mKwxCardGroup.cards = arrays;
                return;
            }
        }
    };

    that.matchAnyPair = function(cards, laizi, branchArray){
        for (var i = 0; i < cards.length; i++){
            var card = cards[i];
            var arrays = [card, card];

            var findCard = that.findCardUseLaizi(cards, laizi, arrays);
            if (findCard[0] == 1){
                branchArray.cardsLeft = findCard[2];
                branchArray.laiziCount = laizi - findCard[1];
                branchArray.mKwxCardGroup.type = that.grouptype_pair;
                branchArray.mKwxCardGroup.cards = arrays;
                return;
            }
        }
    };

    //index:0 0失败,1成功   index:1 使用癞子数量
    that.findCardUseLaizi = function(resultCards, laizi, findNums){
        var result = [0, 0, null];
        var cards = resultCards.slice(0);

        var isFinds = [];
        var notFindCount = 0;
        for (var i = 0; i < findNums.length; i++){
            var isFind = cards.indexOf(findNums[i]) != -1;
            isFinds.push(isFind);

            if (!isFind){
                notFindCount++;
            }else{
                cards.splice(cards.indexOf(findNums[i]), 1);
            }
        }

        if (notFindCount > laizi){
            //未找到
        }else{
            //找到了
            result[0] = 1;
            result[1] = notFindCount;
            result[2] = cards;
        }

        return result;
    };

    that.getSuite = function(card){
        if (card > 20 && card < 30){
            return 0;
        }else if (card > 40 && card < 50){
            return 1;
        }else if (card > 60 && card < 70){
            return 2;
        }else if (card > 80 && card < 90){
            return 3;
        }
        return -1;
    };

    that.findLackCard = function(inhandCards, safaCards){
        var map = {};
        for (var i = 0; i < inhandCards.length; i++){
            var card = inhandCards[i];
            if (map[card.toString()] == undefined){
                map[card.toString()] = 0;
            }
            map[card.toString()] += 1;
        }


        //风
        for (var i = 0; i < 3; i++){
            var cardNum = i + 85;
            if (map[cardNum.toString()] == 1){
                if (mo.gameHelper.findValueForArray(safaCards, cardNum) != null){
                    return cardNum;
                }
            }
        }

        var numLack2 = [];
        var numLack1 = [];

        //花
        var nums = [1, 9, 2, 8, 3, 7, 4, 6, 5];
        for (var i = 0; i < 3; i++){
            for (var j = 0; j < 9; j++){
                var cardNum = 20 + i * 20 + nums[j];
                if (map[cardNum.toString()] == 1){
                    //第一步
                    var isFrist = true;
                    for (var m = 0; m < 2; m++){
                        var temp = -1 + cardNum + m * 2;
                        if (map[temp.toString()] != undefined){
                            isFrist = false;
                            break;
                        }
                    }

                    if (isFrist){
                        numLack1.push(cardNum);
                        for (var m = 0; m < 2; m++){
                            var temp = -2 + cardNum + m * 4;
                            if (map[temp.toString()] != undefined){
                                isFrist = false;
                                break;
                            }
                        }
                    }

                    if (isFrist) {
                        numLack2.push(cardNum);
                    }
                }
            }
        }

        for (var i = 0; i < numLack2.length; i++){
            var cardNum = numLack2[i];
            if (map[cardNum.toString()] == 1){
                if (mo.gameHelper.findValueForArray(safaCards, cardNum) != null){
                    return cardNum;
                }
            }
        }

        for (var i = 0; i < numLack1.length; i++){
            var cardNum = numLack1[i];
            if (map[cardNum.toString()] == 1){
                if (mo.gameHelper.findValueForArray(safaCards, cardNum) != null){
                    return cardNum;
                }
            }
        }

        return -1;
    };

    return that;
};